package com.xcf.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

/**
 * JsonUtil <br>
 *
 * @author xiaocf <br>
 * @version 1.0 <br>
 * @date 2020/8/3 15:27 <br>
 */
public class JsonUtil {

    private static ObjectMapper mapper = new ObjectMapper( );

    private static class ListTypeReference<T> extends TypeReference<List<T>> {
    }

    public static <T> List<T> toList(String json) {
        if (null == json || "".equals(json)) {
            return null;
        }
        try {
            return mapper.readValue(json, new ListTypeReference<T>( ));
        } catch (JsonProcessingException e) {
            e.printStackTrace( );
        }
        return null;
    }

    public static void main(String[] args) {
        List<Integer> list = JsonUtil.toList("[2,4,5,8,10]");
        Integer[] ints = list.toArray(new Integer[0]);
        for (Integer anInt : ints) {
            System.out.println("anInt = " + anInt);
        }

        List<List<Integer>> objects = JsonUtil.toList("[[1,0,0],[1,1,0],[1,1,1]]");
        for (List<Integer> object : objects) {
            for (Integer integer : object) {
                System.out.println("integer = " + integer);
            }
        }
    }
}
